import json
import os

from frame.api.base_api import BaseApi
from frame.utils.log_utils import logger
from frame.utils.utils import Utils


class BaseAdmin(BaseApi):
    """
    admin基类的封装
    """

    admin_url = "admin/"

    def __init__(self):
        frm_path = Utils.get_frame_root_path()
        file_path = os.sep.join([frm_path, '/data/login.yaml'])
        yaml_data = Utils.get_yaml_data(file_path)
        # _env = os.getenv("test_env")
        # logger.info(_env)
        username = yaml_data.get("admin").get('username')
        password = yaml_data.get("admin").get('password')
        data = {
            "username": username,
            "password": password
        }
        req = {
            "method": "post",
            "url": self.BASE_URL + self.admin_url + "auth/login",
            "json": data
        }
        res = self.do_send(req)
        self.token = res.json().get("data").get("token")

    def send_api(self, req):
        start_url = ""
        # 请求头中添加token
        if req.get("headers"):
            req['headers']['X-Litemall-Admin-Token'] = self.token
        else:
            req['headers'] = {
                "X-Litemall-Admin-Token": self.token
            }
        if req.get("url"):
            start_url = req.get("url")
            req['url'] = self.BASE_URL + self.admin_url + start_url
        res = self.do_send(req)
        logger.info(f"{start_url}接口的响应结果为:{json.dumps(res.json(), indent=2, ensure_ascii=False)}")
        return res
